// OGoMojo
// Whitemice.MOGI.Logger.RPC2
// License: LGPL
// Copyright: Whitemice Consulting, 2006
// Author(s): Adam Tauno Williams (awilliam@whitemice.org)
using System;
using System.IO;
using CookComputing.XmlRpc;

namespace Whitemice.MOGI.RPC2
{
	/// \brief Provides a simple implementation of the IEventLog interface
	public class EventLog : IEventLog
	{
		protected	StreamWriter	logFile;
		protected	uint		logLevel;		
		
		/// \brief Constructor
		/// \param filename File to log to
		public EventLog(string filename)
		{
			Level = 100;
			logFile = new StreamWriter(File.Open(filename, FileMode.Append, FileAccess.Write, FileShare.ReadWrite));
		}
		
		~EventLog()
		{
			logFile.Flush();
			logFile.Close();
		}
				
		/// \brief Level property
		/// \note This controls the minimum level of messages that will be recorded to the log
		public uint Level
		{
			get { return logLevel; }
			set { logLevel = value; }
		}
		
		/// \brief Accepts a message to log
		/// \brief level Importance level of the message
		/// \brief message The message to log
		public void LogMessage(uint level, string message)
		{
			if (level >= Level)
				Write(level.ToString() + " " + message);
		}

		/// \brief Records exception information to the log
		/// \param exception The exception to unwind and record
		public void LogException(Exception exception)
		{
			uint counter = 1;
			
			Write("X 0 " + exception.Message);
			while (exception.InnerException != null)
			{
				exception = exception.InnerException;
				Write("X " + counter.ToString() + ":" + exception.Message);
				if (exception is XmlRpcFaultException)
				{
					Write("X " + counter.ToString() + "  FaultCode=" + ((XmlRpcFaultException)exception).FaultCode);
					Write("X " + counter.ToString() + "  FaultMessage=" + ((XmlRpcFaultException)exception).FaultString);
				}
				counter++;
			}
		}
		
		/// \brief Write the specified message to the log file
		/// \param message Message to record
		protected void Write(string message)
		{
			if (logFile != null)
			{
				logFile.WriteLine(DateTime.Now.ToString() + " " + message);
				logFile.Flush();
			}
			Console.WriteLine(message);
		}
		
		public void Close()
		{
			logFile.Close();
			logFile = null;
		}
	}
}
